package excel;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelToText {
	public static void main(String[] args) throws FileNotFoundException,
			IOException {

		ArrayList<String> content = new ArrayList<>();

		InputStream ExcelFileToRead = new FileInputStream(args[0]);
		HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);

		HSSFSheet sheet = wb.getSheetAt(0);
		HSSFRow row;
		HSSFCell cell;

		Iterator rows = sheet.rowIterator();

		while (rows.hasNext()) {
			row = (HSSFRow) rows.next();
			Iterator cells = row.cellIterator();

			while (cells.hasNext()) {
				cell = (HSSFCell) cells.next();

				if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
					content.add(cell.getStringCellValue());
					// System.out.print(cell.getStringCellValue() + " ");
				} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
					// System.out.print(cell.getNumericCellValue() + " ");
				} else {
					// U Can Handel Boolean, Formula, Errors
				}
			}

		}
		// content.get(i)
		Writer writer = null;
		
		String inputFileName = args[0].substring(args[0].lastIndexOf("\\") + 1, args[0].lastIndexOf("."));
		System.out.print("inputFileName : " + inputFileName);
		for (int i = 0; i < content.size(); i++) {
//			System.out.print(content.get(i));
			try {
				writer = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(args[1] + "/" + inputFileName + " (" + (i + 1) + ").txt"), "utf-8"));
				writer.write(content.get(i));
			} catch (IOException ex) {
				// report
			} finally {
				try {
					writer.close();
				} catch (Exception ex) {
				}
			}
		}

		System.out.println("Finish");
	}

}
